//
//  WBOAuthViewController.swift
//  传智微博
//
//  Created by zhoujiming on 2017/2/8.
//  Copyright © 2017年 gmcc. All rights reserved.
//

import UIKit
import SVProgressHUD

// 通过webview加载新浪微博授权页面
class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        view.backgroundColor = UIColor.white
        
        webView.scrollView.isScrollEnabled = false
        
        // 设置代理
        webView.delegate = self
        
        // 设置导航栏
        title = "登录新浪微博"
        
        // 导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        
        // 确定要访问的资源
        guard let url = URL(string: urlString) else {
                
                return
        }
        
        // 建立请求
        let request = URLRequest(url: url)
        
        // 加载请求
        webView.loadRequest(request)
        
    }
    
    @objc fileprivate func close(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    // 自动填充 webview的注入，直接通过js修改本地浏览器中页面元素的内容
    @objc private func autoFill(){
        // 准备js
        let js = "document.getElementById('userId').value='zhouxthz@163.com';" +
            "document.getElementById('passwd').value='zhou021585';"
        // 让webview执行
        webView.stringByEvaluatingJavaScript(from: js)
    }

}

extension WBOAuthViewController : UIWebViewDelegate{
    
    
    /// 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: <#webView description#>
    ///   - request: <#request description#>
    ///   - navigationType: <#navigationType description#>
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //print("加载请求-----\(request.url?.absoluteString)")
        
        // 如果地址包含baidu.com，不加载页面，否则，加载页面
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false{
            return true
        }
        
        // 查找'code='字符串
        // 如果有code，则说明授权成功
        if request.url?.query?.hasPrefix("code=") == false{
            //print("取消授权")
            close()
            return false
        }
        // 从query中获取授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("获取授权码:\(code)")
        
        // 使用授权码获取accesstoken
        WBNetworkManager.shared().loadAccessToken(code: code){(isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败！")
            }
            else
            {
                // SVProgressHUD.showInfo(withStatus: "登录成功")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserLogonSuccessNotification), object: nil)
                // 跳转到
                self.close()
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
